package site.qjdb.util;

import site.qjdb.constant.Info;
import site.qjdb.pojo.User;
import site.qjdb.pojo.response.CommonResult;
import site.qjdb.service.UserService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

/**
 * 通用工具类
 *
 */
public class CommonUtils {

	/**
	 * 格式化时间返回yyyy-MM-dd HH:mm:ss
	 */
	public static String formatNow() {
		LocalDateTime currentTime = LocalDateTime.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		return currentTime.format(formatter);
	}

	/**
	 * 格式化时间返回，自定义格式
	 */
	public static String formatNow(String format) {
		LocalDateTime currentTime = LocalDateTime.now();
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
		return currentTime.format(formatter);
	}

	/**
	 * 	获取请求主机IP地址
	 *
	 */
	public static String getIpAddress(HttpServletRequest request) throws IOException {
		// 如果通过代理进来，则透过防火墙获取真实IP地址;
		String ip = request.getHeader("X-Forwarded-For");

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
		} else if (ip.length() > 15) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = (String) ips[index];
				if (!("unknown".equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}
		return ip;
	}

	/**
	 * List<String>转字符串
	 *
	 */
	public static String listToString(List<String> list, String separate) {
		String str = "";
		if (list != null && list.size() > 0) {
			if (list.size() == 1) {
				str = list.get(0);
			} else {
				int i = 0;
				for (i = 0; i < list.size() - 1; i++) {
					str = str + list.get(i) + separate;
				}
				str = str + list.get(i);
			}
		}
		return str;
	}

	/**
	 * 校验字符串是否为空
	 *
	 */
	public static boolean isEmpty(String str) {
		if (str == null || "".equals(str)) {
			return true;
		}
		return false;
	}

	/**
	 * 校验字符串是否为空
	 *
	 */
	public static boolean isEmpty(String str, boolean strict) {
		if (strict) {
			if (str == null || "".equals(str) || "".equals(str.trim())) {
				return true;
			}
			return false;
		}
		return isEmpty(str);
	}

	/**
	 * 生成不重复的32位小写字符串
	 *
	 * @return
	 */
	public static String uuid() {
		return UUID.randomUUID().toString().replace("-", "").toLowerCase();
	}




	//========================================= 老项目迁移 =========================================

	/**
	 * 	处理session和cookie过期问题
	 *
	 * 	判断session和cookie是否都过期了，并进行处理：
	 * 	1.session和cookie都过期了，不做任何处理--> 返回0
	 * 	2.若session没过期，不做任何处理--> 返回1
	 * 	3.session过期了，则根据cookie里的信息在session中添加用户信息
	 * 		3.1添加成功，返回新的cookie--> 返回2
	 * 		3.2添加失败，cookie中的用户信息与数据库中的信息不匹配--> 返回0
	 * 	4.cookie里的sno格式不正确返回--> 返回0
	 *
	 * 	参数：
	 * 	userSessionKey：在session中保存用户信息的key
	 * 	userCookieKey：在cookie中保存用户信息的key
	 * 	separator：在cookie中key对应的value的分隔符
	 *
	 * */
	public static int handleSCExpire(Cookie[] cookies,
									 HttpSession session,
									 HttpServletResponse response,
									 UserService userService) {
		if(session.getAttribute(Info.USER_SESSION) != null) {
			return 1;
		}
		String cookieValue = getCookieValue(cookies, Info.USER_COOKIE);
		if(cookieValue == null) {
			return 0;
		}
		String sno = cookieValue.split(Info.USER_COOKIE_SEPARATOR)[0];
		String pwd = cookieValue.split(Info.USER_COOKIE_SEPARATOR)[1];
		if(!sno.matches("^[1-9]\\d{12}$")) {
			// 非法登录
			return 0;
		}
		User _user = new User();
		_user.setSno(new Long(sno));
		_user.setPwd(pwd);
		CommonResult<User> result = userService.loginByCookie(_user);
		int code = result.getCode();
		if(code == 200) {
			// 登录成功
			// 设置Cookie
			setLoginCookie(sno + Info.USER_COOKIE_SEPARATOR + pwd, response, Info.USER_COOKIE);
			// 在session中保存用户的登录状态
			session.setAttribute(Info.USER_SESSION, result.getData());
			return 2;
		} else {
			return 0;
		}
	}

	/**
	 * 	设置Cookie，最大存活时间默认为14天
	 * 	value：要设置的内容
	 *
	 * */
	public static void setLoginCookie(String value,
									  HttpServletResponse response,
									  String userCookieKey) {
		Cookie cookie = new Cookie(userCookieKey, value);
		// 设置最大存活时间为14天
		cookie.setMaxAge(60 * 60 * 24 * 14);
		// 设置Cookie路径
		cookie.setPath("/"); // 默认为父路径
		response.addCookie(cookie);
	}

	/**
	 * 	从Cookie中根据key获取value，找不到则返回NULL
	 * 	cookies：cookies
	 * 	key：键
	 *
	 *
	 * */
	private static String getCookieValue(Cookie[] cookies, String key) {
		String value = null;
		if (cookies != null && cookies.length > 0) {
			for (Cookie c : cookies) {
				if (c.getName().equals(key)) {
					value = c.getValue();
					break;
				}
			}
		}
		return value;
	}






}
